<?php
require_once('functions.php');

function getCAddresses()
{
	$conn = getConnection();
	return $conn->query('SELECT * FROM Customer_Address');
}

function getCAddress($row)
{ 
		$conn = getConnection();
        $results = $conn->query("SELECT * FROM Customer_Address WHERE user_ID='$row[user_ID]' AND street='$row[street]' AND zipCode='$row[zipCode]'");
        $row = $results->fetch_assoc();
        $conn->close();
        return $row;
}

function blankAddress($id)
{
	return array('user_ID' => $id, 'zipCode' => null, 'street' => null, 'city' => null, 'type' => null, 'state_province' => null, 'country' => null);
} 


function noAddress()
{
	$conn = getConnection();
	$sql = "SELECT u.user_ID, firstName, secondName FROM User u LEFT JOIN Customer_Address ca ON u.user_ID = ca.user_ID WHERE ca.user_ID IS NULL";
	$results = $conn->query($sql);
    $conn->close();
       
    return $results;
}
function deleteAddress($id, $street, $zipCode)
{
		$conn = getConnection();
		$conn->query("DELETE FROM Customer_Address WHERE user_ID = '$id' AND street = '$street' AND zipCode = '$zipCode'");
		$conn->close();
		header('Location: index.php');
}
		
function saveAddress($row)
{
        $conn = getConnection();
        $row2 = escapeRow($row, $conn);
        
        if (getCAddress($row2))
        	$sql =  "UPDATE Customer_Address SET type='$row2[type]', street='$row2[newStreet]', city='$row2[city]', state_province='$row2[state_province]', zipCode='$row2[newZipCode]', country='$row2[country]' WHERE user_ID= '$row2[user_ID]' AND zipCode='$row2[zipCode]' AND street='$row2[street]'";
       	else
       	{
	       	$sql =  "INSERT INTO Customer_Address (user_ID, zipCode, type, street, city, state_province, country) "
	        ."VALUES ('$row2[user_ID]', '$row2[newZipCode]', '$row2[type]', '$row2[newStreet]', '$row2[city]', '$row2[state_province]', '$row2[country]')";
		}
        $results = $conn->query($sql);
        $error = $conn->error;
        $conn->close();
       
        return $error == '' ? true : array('SQL Error' => $error);
}

